import 'package:flutter/material.dart';
import 'dart:convert';
import '../pages/bottomNav.dart';
import '../pages/listEndLine.dart';
import '../util/DataUtils.dart';
import '../util/ToastUtils.dart';
import '../api/Api.dart';

class MusicList extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return new MaterialApp(
            title: '奇妙时代',
            home: new MusicListPage(),
        );
    }
}


class MusicListPageState extends State<MusicListPage> {
    
    List listData = new List();
    var curPage = 1;
    var listTotalSize = 0;
    ScrollController _controller = new ScrollController();
    TextStyle titleTextStyle = new TextStyle(fontSize: 15.0);
    TextStyle subtitleStyle = new TextStyle(color: const Color(0xFFB5BDC0), fontSize: 12.0);
    final String END_LINE_TAG = "COMPLETE";
    

    MusicListPageState() {
        print('MusicListPageState构造函数...');
        _controller.addListener(() {
            var maxScroll = _controller.position.maxScrollExtent;
            var pixels = _controller.position.pixels;
            if (maxScroll == pixels && listData.length - 1 < listTotalSize) {
                // scroll to bottom, get next page data
                print("加载更多 ... ");
                curPage++;
                getList(true);
            }
        });
    }

    getList(bool isLoadMore) {
        
        if(!isLoadMore) {
            listData.clear();
            listData.insert(0, END_LINE_TAG);
        }
        
        Map<String, String> _param = new Map();
        _param['page'] = curPage.toString();
        DataUtils.netPost(Api.MUSIC_LIST_API, params: _param).then((data) {
            print(data);
            if (data != null) {
                try {
                    Map<String, dynamic> map = json.decode(data);
                    if (map['code'] == 1) {
                        var _data = map['data'];
                        listTotalSize = _data['total'];
                        var _listData = _data['data'];
                        setState(() {
                            listData.insertAll(listData.length - 1, _listData);
                        });
                    } else {
                        ToastUtils.showAlertDialog(context, map['msg']);
                    }
                } catch( ex ) {
                    print(ex);
                    ToastUtils.showAlertDialog(context, ex.toString());
                }
            }
        });
    }

    @override
    void initState() {
        super.initState();
        print('MusicListPageState--initState...');
        curPage = 1;
        getList(false);
    }

    @override
    void dispose() {
        listData.clear();
        super.dispose();
    }
    
    Future<Null> _pullToRefresh() async {
        curPage = 1;
        getList(false);
        return null;
    }

    Widget renderRow(i) {
        var itemData = listData[i];
        if (itemData is String && itemData == END_LINE_TAG) {
            print('listData.length=' + listData.length.toString() + ',listTotalSize=' + listTotalSize.toString());
            if(listData.length - 1 < listTotalSize) {
                return Container(
                    padding: const EdgeInsets.all(16.0),
                    alignment: Alignment.center,
                    child: SizedBox(
                        width: 24.0,
                        height: 24.0,
                        child: CircularProgressIndicator(strokeWidth: 2.0)
                    ),
                );
            }
            return new ListEndLine();
        }
        var titleRow = new Row(
            children: <Widget>[
                new Expanded(
                    child: new Text(itemData['title'], style: titleTextStyle),
                )
            ],
        );
        var timeRow = new Row(
            children: <Widget>[
                new Container(
                    width: 20.0,
                    height: 20.0,
                    decoration: new BoxDecoration(
                        shape: BoxShape.circle,
                        color: const Color(0xFFFFFFFF),
                        image: new DecorationImage(
                            image: new NetworkImage(itemData['cover_url']), fit: BoxFit.cover),
                        border: new Border.all(
                            color: const Color(0xFFECECEC),
                            width: 2.0,
                        ),
                    ),
                ),
                new Padding(
                    padding: const EdgeInsets.fromLTRB(5.0, 0.0, 0.0, 0.0),
                    child: new Text(
                        itemData['copyright_names'],
                        style: subtitleStyle,
                    ),
                ),
                new Expanded(
                    flex: 1,
                    child: new Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                            new Text(itemData['play_total'] * 1 > 0 ? "播放次数：${itemData['play_total']}次" : '', style: subtitleStyle),
                        ],
                    ),
                )
            ],
        );
        var thumbImgUrl = itemData['cover_url'];
        var thumbImg = new Container(
            margin: const EdgeInsets.all(10.0),
            width: 60.0,
            height: 60.0,
            decoration: new BoxDecoration(
                shape: BoxShape.circle,
                color: const Color(0xFFFFFFFF),
                image: new DecorationImage(
                    image: new ExactAssetImage('images/ic_img_default.jpg'),
                    fit: BoxFit.cover),
                border: new Border.all(
                    color: const Color(0xFFECECEC),
                    width: 2.0,
                ),
            ),
        );
        if (thumbImgUrl != null && thumbImgUrl.length > 0) {
            thumbImg = new Container(
                margin: const EdgeInsets.all(10.0),
                width: 60.0,
                height: 60.0,
                decoration: new BoxDecoration(
                    shape: BoxShape.circle,
                    color: const Color(0xFFFFFFFF),
                    image: new DecorationImage(
                        image: new NetworkImage(thumbImgUrl), fit: BoxFit.cover),
                    border: new Border.all(
                        color: const Color(0xFFECECEC),
                        width: 2.0,
                    ),
                ),
            );
        }
        var row = new Row(
            children: <Widget>[
                new Expanded(
                    flex: 1,
                    child: new Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: new Column(
                            children: <Widget>[
                                titleRow,
                                new Padding(
                                    padding: const EdgeInsets.fromLTRB(0.0, 8.0, 0.0, 0.0),
                                    child: timeRow,
                                )
                            ],
                        ),
                    ),
                ),
                new Padding(
                    padding: const EdgeInsets.all(6.0),
                    child: new Container(
                        width: 100.0,
                        height: 80.0,
                        color: const Color(0xFFFCFCFC),
                        child: new Center(
                            child: thumbImg,
                        ),
                    ),
                ),
            ],
        );
        return new InkWell(
            child: new Column(
                children: <Widget>[
                    row,
                    new Divider(height: 1.0),
                ],
            ),
            onTap: () {
                //Navigator.of(context).push(new MaterialPageRoute(
                //    builder: (ctx) => new NewsDetailPage(id: itemData['detailUrl'])
                //));
                print('ROW-ONTAP--ID:' + itemData['id'].toString());
                ToastUtils.showMsg('Music-Id:' + itemData['id'].toString());
            },
        );
    }
    
    Widget mainWidget() {
        if (listData == null) {
            return new Center(
                child: new CircularProgressIndicator(),
            );
        } else {
            Widget listView = new ListView.builder(
                itemCount: listData.length,
                itemBuilder: (context, i) => renderRow(i),
                controller: _controller,
            );
            return new RefreshIndicator(child: listView, onRefresh: _pullToRefresh);
        }
    }
    
    Widget build(BuildContext context) {
        
        return new Scaffold (
            appBar: new AppBar(
                title: new Text('奇妙时代'),
            ),
            body: mainWidget(),
            bottomNavigationBar: new BottomNav(0),
        );
        
    }
}

class MusicListPage extends StatefulWidget {
    @override
    createState() => new MusicListPageState();
}